<?php
/**
 * Created by PhpStorm.
 * User: Lxx<779219930@qq.com>
 * Date: 2018/10/31
 * Time: 15:38
 */

namespace app\home\controller;


use app\admin\model\Push;
use app\home\model\WechatUser;
use com\wechat\TPQYWechat;
use think\Config;
use think\Controller;
use think\Exception;
use think\Log;

/**
 * Class Index
 * @package app\home\controller
 * 主页-菜单列表及入口
 */
class Index extends Controller
{
    public function index() {

        return $this->fetch();
    }

    /**
     * 用户登入获取信息
     */
    public function login(){
        // 获取用户信息
        $Wechat = new TPQYWechat(config('user'));
        $result = $Wechat->getUserId(input('code'), config('user.agentid'));
        if(empty($result['UserId'])) {
            session('userId', 'visitor');//游客userid为0
            session('name', '游客');
        } else {
            $userInfo = $Wechat->getUserInfo($result['UserId']);
            $data = [
                'userid' => $userInfo['userid'],
                'name' => $userInfo['name'],
                'mobile' => $userInfo['mobile'],
                'gender' => $userInfo['gender'],
                'avatar' => $userInfo['avatar'],
                'department' => $userInfo['department'][0], //只选第一个所属部门
                'status' => $userInfo['status'],
                'order' => $userInfo['order'][0],
            ];

            if(isset($userInfo['extattr']['attrs'])) {
                foreach ($userInfo['extattr']['attrs'] as $value) {
                    switch ($value['name']){
                        case "权限":
                            $data['permission'] = $value['value'] ? $value['value'] : 5;
                            break;
                        default:
                            break;
                    }
                }
                $data['extattr'] = json_encode($userInfo['extattr']);
            }else {
                $data['extattr'] = json_encode($userInfo['extattr']);
            }

            $wechatUser = new WechatUser();
            if ($wechatUser->checkUserExist($userInfo['userid'])) {
                $wechatUser->save($data, ['userid' => $userInfo['userid']]);
            } else {
                $wechatUser->save($data);
            }

            session('userId', $userInfo['userid']);
            session('name', $userInfo['name']);
            session('gender', $userInfo['gender']);
            session('avatar', $userInfo['avatar']);
            session('department', $userInfo['department'][0]);

            $this->redirect(session('requestUri'));
        }
    }

    public function push()
    {
        $map = ['status' => 0];
        $list = Push::where($map)->select();
        foreach ($list as $value) {
            //发送给服务号
            $Wechat = new TPQYWechat(Config::get($value['agentname']));
            $message = array(
                "touser" => $value['touser'],
                "msgtype" => $value['msgtype'],
                "agentid" => $value['agentid'],
                $value['msgtype'] => (array)json_decode($value['sendcontent']),
                "safe" => "0"
            );
            try {
                $msg = $Wechat->sendMessage($message);
                if ($msg['errcode'] == 0){
                    Push::where('id',$value['id'])->update(['status' => 1,'update_time' => time()]);
                    Log::write("审批消息发送：发送成功");
                }else{
                    Log::write("审批消息发送：发送失败");
                }
                Log::write($msg);
            }catch (Exception $exception) {
                $msg = $exception->getMessage();
                Log::write("消息发送崩溃：发送失败".$msg);
            }
        }
    }
}